/* components */
import { BaseSelectUserTreeComponent, BaseSelectUserNoDataView } from '@src/component/common/BaseSelectUser/components'
/* enum */
import { BaseSelectUserComponentNameEnum, SelectUserComponentDepartment } from '@src/component/common/BaseSelectUser/model'
/* hooks */
import { 
  useBaseSelectUserStoreCurrentDepartmentNav, 
  useBaseSelectUserStoreDepartmentData, 
  useBaseSelectUserStoreFilterForm, 
  useBaseSelectUserStoreLoadingMap, 
  useBaseSelectUserStoreUserListMap 
} from '@src/component/common/BaseSelectUser/store'
import { 
  useBaseSelectUserDepartmentUserListParams, 
  useBaseSelectUserFilter, 
  useBaseSelectUserOptions, 
  useFetchDepartmentUserList, 
  useSelectUserChecked, 
  useSelectUserCheckedItemList,
  useSelectUserIsShowCheckbox
} from '@src/component/common/BaseSelectUser/hooks'
/* scss */
import '@src/component/common/BaseSelectUser/components/Department/index.scss'
/* vue */
// @ts-ignore
import { ComponentInstance, ComponentRenderProxy, computed, defineComponent, PropType } from 'vue'
import { CommonComponentInstance } from '@model/VC'
import { CreateElement } from 'vue'
/* util */
import { isEmpty, isFalse } from '@src/util/type'
import { getCheckedItemId } from '@src/component/common/BaseSelectUser/util'
import { findComponentsDownward } from '@src/util/assist'
import Log from '@src/util/log'

export type DepartmentLeftProps = {
  isMulti: boolean;
  value: SelectUserComponentDepartment[];
}

export interface DepartmentLeftSetupState {
  
}

export enum DepartmentLeftEmitEventNameEnum {
  Input = 'input',
  Click = 'click',
  LoadUser = 'loadUser',
}

export type DepartmentLeftInstance = ComponentInstance & DepartmentLeftSetupState
export type DepartmentLeftVM = ComponentRenderProxy<DepartmentLeftProps> & CommonComponentInstance & DepartmentLeftInstance

export default defineComponent({
  name: BaseSelectUserComponentNameEnum.BaseSelectUserDepartmentLeft,
  emits: [
    DepartmentLeftEmitEventNameEnum.Input,
    DepartmentLeftEmitEventNameEnum.Click,
    DepartmentLeftEmitEventNameEnum.LoadUser
  ],
  props: {
    /* 是否为多选状态 */
    isMulti: {
      type: Boolean as PropType<boolean>,
      default: false
    }
  },
  setup(props: DepartmentLeftProps, { emit }) {
    
    // 部门列表
    const { 
      departmentList, 
      departmentRootList, 
      departmentRootNotDeleteList,
      departmentRootDeleteList,
      isDepartmentRootListEmpty,
      isDepartmentRootListNotEmpty,
      setDepartmentList 
    } = useBaseSelectUserStoreDepartmentData()
    // 部门人员列表
    const { setDepartmentUserList } = useBaseSelectUserStoreUserListMap()
    // 导航
    const { currentDepartmentNav, setCurrentDepartmentNav } = useBaseSelectUserStoreCurrentDepartmentNav()
    // 部门人员列表页数据
    const { resetPageNum } = useBaseSelectUserDepartmentUserListParams()
    // 加载状态
    const { departmentLoading, tabLoading, setDepartmentLoading, clearDepartmentLoading } = useBaseSelectUserStoreLoadingMap()
    // 筛选
    const { isFilterDepartmentFormTagNameEmpty } = useBaseSelectUserStoreFilterForm()
    // 已选中数据
    const { addCheckedItem, removeCheckedItem, checkedDepartmentItemList } = useSelectUserCheckedItemList()
    // 复选框
    const { isShowDepartmentCheckbox } = useSelectUserIsShowCheckbox()
    
    // 获取部门人员列表
    const fetchDepartmentUserList = useFetchDepartmentUserList()
    
    /** 
     * @description 是否显示部门列表无数据页面
     * 1. 部门列表为空
     * 2. 且 不在加载状态
    */
    const isShowDepartmentListNotDataView = computed(() => {
      return isDepartmentRootListEmpty.value && isFalse(departmentLoading.value)
    })
    
    /** 
     * @description 是否不显示部门列表无数据页面
    */
    const isNotShowDepartmentListNotDataView = computed(() => {
      return isFalse(isShowDepartmentListNotDataView.value) && isDepartmentRootListNotEmpty.value
    })
    
    const isDepartmentRootNotDeleteListEmpty = computed(() => {
      return isEmpty(departmentRootNotDeleteList.value)
    })
    
    const isDepartmentRootNotDeleteListNotEmpty = computed(() => isFalse(isDepartmentRootNotDeleteListEmpty.value))
    
    const currentNodeKey = computed(() => currentDepartmentNav.value?.id)
    
    const defaultExpandedKeys = computed(() => {
      
      // 存在部门名称筛选项，则不需要默认展开第一级
      if (isFalse(isFilterDepartmentFormTagNameEmpty.value)) {
        return []
      }
      
      // 默认展开第一级
      return departmentRootNotDeleteList.value.map(item => item.id)
    })
    
    const defaultCheckedKeys = computed(() => {
      return checkedDepartmentItemList.value.map(item => getCheckedItemId(item))
    })
    
    const clearDepartmentUserList = () => {
      setDepartmentUserList()
    }
    
    const onDepartmentItemClickHandler = (value: SelectUserComponentDepartment) => {
      
      setCurrentDepartmentNav(value)
      
      resetPageNum()
      
      const isInit = true
      
      fetchDepartmentUserList(isInit).then(() => {
        emit(DepartmentLeftEmitEventNameEnum.LoadUser)
      })
      
    }
    
    return {
      currentNodeKey,
      
      departmentList,
      departmentRootList,
      departmentRootNotDeleteList,
      departmentRootDeleteList,
      
      defaultCheckedKeys,
      defaultExpandedKeys,
      
      departmentLoading,
      tabLoading,
      
      isShowDepartmentCheckbox,
      isDepartmentRootNotDeleteListEmpty,
      isDepartmentRootNotDeleteListNotEmpty,
      isShowDepartmentListNotDataView,
      isNotShowDepartmentListNotDataView,
      
      onDepartmentItemClickHandler
    }
    
  },
  methods: {
    /** 
    * @description 获取属性列表
    */
    getAttributes() {
      return {
        directives: [
          {
            name: 'loading',
            value: this.departmentLoading && isFalse(this.tabLoading)
          }
        ]
      }
    },
    onDepartmentCommonItemClickHandler(value: SelectUserComponentDepartment) {
      
      this.onDepartmentItemClickHandler(value)
      
      const elTreeNodeComponents = findComponentsDownward(this.$refs.BaseSelectUserDepartmentDeleteTree, 'ElTreeNode')
      
      this.clearCurrentNodeHighlight(elTreeNodeComponents)
      
    },
    onDepartmentDeleteItemClickHandler(value: SelectUserComponentDepartment) {
      
      this.onDepartmentItemClickHandler(value)
      
      const elTreeNodeComponents = findComponentsDownward(this.$refs.BaseSelectUserDepartmentTree, 'ElTreeNode')
      
      this.clearCurrentNodeHighlight(elTreeNodeComponents)
    },
    clearCurrentNodeHighlight(elTreeNodeComponents: Record<string, any>[]) {
      try {
        
        elTreeNodeComponents.forEach((item: Record<string, any>) => {
          item.node.isCurrent = false
        })
        
      } catch (error) {
        Log.error(error, this.clearCurrentNodeHighlight.name)
      }
    }
  },
  render(h: CreateElement) {
    
    const attrs = this.getAttributes()
    
    return (
      <div class={BaseSelectUserComponentNameEnum.BaseSelectUserDepartmentLeft} {...attrs}>
          <div 
            class="base-select-user-height-100-percent base-select-user-department-tab-root" 
            v-show={this.isNotShowDepartmentListNotDataView}
          >
            
            <BaseSelectUserTreeComponent
              v-show={this.isDepartmentRootNotDeleteListNotEmpty}
              ref="BaseSelectUserDepartmentTree"
              class="base-select-user-department-list-tree"
              data={this.departmentRootNotDeleteList}
              current-node-key={this.currentNodeKey}
              default-expanded-keys={this.defaultExpandedKeys}
              default-checked-keys={this.defaultCheckedKeys}
              is-multi={this.isMulti}
              show-checkbox={this.isShowDepartmentCheckbox}
              onClick={this.onDepartmentCommonItemClickHandler}
            />
            
            {/* start 无数据显示 */}
            <BaseSelectUserNoDataView v-show={this.isDepartmentRootNotDeleteListEmpty} />
            {/* end 无数据显示 */}
            
            <BaseSelectUserTreeComponent
              ref="BaseSelectUserDepartmentDeleteTree"
              class="base-select-user-department-tab-department-delete"
              current-node-key={this.currentNodeKey}
              data={this.departmentRootDeleteList}
              is-multi={this.isMulti}
              onClick={this.onDepartmentDeleteItemClickHandler}
            />
            
          </div>
          
          {/* start 无数据显示 */}
          <BaseSelectUserNoDataView v-show={this.isShowDepartmentListNotDataView} />
          {/* end 无数据显示 */}
      </div>
    )
  }
})
